import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'

import subscript from 'markdown-it-sub'
import superscript from 'markdown-it-sup'
import footnote from 'markdown-it-footnote'
import container from 'markdown-it-container'
import abbreviation from 'markdown-it-abbr'
import insert from 'markdown-it-ins'
import mark from 'markdown-it-mark'
import toc from 'markdown-it-toc'
import miip from 'markdown-it-images-preview'
import emoji from 'markdown-it-emoji'
import tasklists from 'markdown-it-task-lists'
import deflist from 'markdown-it-deflist'
import attrs from 'markdown-it-attrs'
import table from 'markdown-it-multimd-table'
import mdSmartArrows from 'markdown-it-smartarrows'


const md: any = new MarkdownIt({
    breaks: true,   // 自动换行
    typographer:  true,
    highlight: function (code, language) {      
        if (language && hljs.getLanguage(language)) {
          try {
            return `<pre><code class="hljs language-${language}">` +
              hljs.highlight(code, { language  }).value +
              '</code></pre>';
          } catch (__) {}
        }
    
        return '<pre class="hljs"><code>' + md.utils.escapeHtml(code) + '</code></pre>';
    }
})
.use(subscript)  // 下标
.use(superscript)  // 上标
.use(footnote)   // 脚标
.use(mark)   // 标记
.use(insert)   // 插入
.use(miip)    // 图片预览（似乎只是本地的图片）
.use(container, 'spoiler', {   // 自定义块容器
  validate: function(params: string) {
    return params.trim().match(/^spoiler\s+(.*)$/);
  },
  render: function (tokens: any, idx: number) {
    var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
    if (tokens[idx].nesting === 1) {
      // opening tag
      return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
    } else {
      // closing tag
      return '</details>\n';
    }
  }
})
.use(abbreviation)    // 缩写注释
.use(toc)     // 目录
.use(emoji)     // emoji
.use(deflist)    //自定义表格
.use(tasklists,{enabled: true,label: true, labelAfter: true})  //任务列表
.use(attrs,{
  leftDelimiter: '{',
  rightDelimiter: '}',
  allowedAttributes: []  // empty array = all attributes are allowed
})  
.use(table, {
  multiline:  true,
  rowspan:    true,
  headerless: true,
  multibody:  true,
  aotolabel:  true,
})
.use(mdSmartArrows) 

export default md
